package hhpoll.validation;

import java.util.Date;

import hhpoll.domain.Poll;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class PollValidator implements Validator {
	
	public PollValidator() {
	}
	

	@Override
	public boolean supports(Class clazz) {
		return Poll.class.equals(clazz);
	}

	@Override
	public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors, "startDate", "startDate.not.null");
        ValidationUtils.rejectIfEmpty(errors, "endDate", "endDate.not.null");
	}
	
	public void validateActive(Object obj, Errors errors) {
		Poll poll = (Poll)obj;
		Date now = new Date();
		if (poll.getStartDate().after(now))
			errors.reject("poll.pending", "Poll has not yet started");
		if (poll.getEndDate().before(now))
			errors.reject("poll.finished", "Poll has already finished");
	}

}
